package com.bcsp.xml;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;

public class Test8 {

    public static void main(String[] args) throws Exception{
        //删除节点
        //使用dom4j
        //获取文件路径
        String path = Test6.class.getClassLoader().getResource("").getPath();

        //b_out.xml
        //准备SAXReader
        SAXReader reader = new SAXReader();
        //读取文档
        Document document = reader.read(new File(path+"b.xml"));
        //获取根节点
        Element root = document.getRootElement();
        //删除ID为1的元素
        //根据id去查找元素
        Element el = root.elementByID("1");
        root.remove(el);

        //格式化
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        //xml输出流
        XMLWriter writer = new XMLWriter(new FileWriter(path+"b_out.xml"),format);
        //输出
        writer.write(document);
        //关闭流
        writer.close();
    }
}
